<?php


namespace app\admin\model;


use think\facade\Request;
use think\Model;

class Token extends Model
{
    protected $autoWriteTimestamp = true;

    public static function SaveToken($res):bool
    {
        $device_id = Request::header("user-agent");
        $device_type = get_device_type();
        $arr = [
            "staff_no" => $res["StaffNumber"],
            "token" => $res["Token"],
            "expire_time" => strtotime($res["ExpireTime"]),
            "agent" => Request::header("user-agent"),
            "ip" => Request::ip(),
            "device_id" => $device_id,
            "device_type" => $device_type
        ];

        $to = Token::where("staff_no",$res["StaffNumber"])->where("device_type",$device_type)->find();
        if ($to){
            $resData = $to->save($arr);
        }else{
            $resData = Token::create($arr);
        }

        if ($resData == false){
            return false;
        }
        return true;
    }

    // 生成token
    public static function generateToken($staffNo,$device_type)
    {
        $Token = sha1(md5(time()).md5(time()));
        $device_id = Request::header("user-agent");
//        $device_type = get_device_type();
        $token_info = Token::where("device_type", $device_type)->where("staff_no",$staffNo)->find();
        if(!$token_info){
            $arr = [
                "staff_no" =>$staffNo,
                "token" => $Token,
                "expire_time" => strtotime("+1 hour"),
                "agent" => Request::header("user-agent"),
                "ip" => Request::ip(),
                "device_id" => $device_id,
                "device_type" => $device_type
            ];
            Token::create($arr);
        }else{
            $token_info->isUpdate(true)->save([
                "expire_time" => strtotime("+1 hour"),
            ]);
            $Token = $token_info["token"];
        }
        return $Token;
    }
}